import React, { memo, useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { Modal, Input, InputNumber, DatePicker, Button, Row } from 'antd';
import { IProps, BatchNumberProps, StockBatchNumber } from './interface';
import styles from './styles.module.scss';
import Table from './../table/Table';
import Icon from './../icon/Icon';
import { TableRefProps } from './../table/interface';
import moment from 'moment';
import { warning } from './../../utils/message/message';

const sotckColumns = [
  { dataIndex: 'batchNumber', width: 120 },
  { dataIndex: 'qty', width: 120 },
  { dataIndex: 'validityDate' }
]

const columns = [...sotckColumns, { dataIndex: 'action', width: 60 }];
const scroll = { y: 370 };

export default memo(({ visible, onCancel, stockBatchNumbers, defaultBatchNumbers, onOk, totalNumber, disabled }: IProps) => {

  const tableRef = useRef<TableRefProps>(null);
  const [batchNumbers, setBatchNumbers] = useState<BatchNumberProps[]>([]);

  useEffect(() => {
    if (defaultBatchNumbers) setBatchNumbers(defaultBatchNumbers);
  }, [defaultBatchNumbers]);

  const move = useCallback(() => {
    const selectionRows: StockBatchNumber[] = (tableRef.current as TableRefProps).getSelectedRows();
    const mapping = batchNumbers.reduce((next, cur) => (next[cur.batchNumber] = true) && next, {});
    setBatchNumbers(batchNumbers.concat(selectionRows.filter(item => !mapping[item.batchNumber])));
  }, [batchNumbers]);

  function syncBatchNumbers(index: number, key: string, value: any) {
    setBatchNumbers(batchNumbers.map((item, cindex) => {
      if (cindex === index) return { ...item, [key]: value };
      return item
    }))
  }

  const addBatchNumber = useCallback(() => {
    setBatchNumbers([
      ...batchNumbers,
      { batchNumber: '', qty: 1, validityDate: moment().format() }
    ])
  }, [batchNumbers]);

  const _onOk = useCallback(() => {
    const filter = batchNumbers.filter(item => {
      return item.batchNumber && item.qty && item.validityDate
    })
    if (filter.length) return warning(window.$app.t('batchNumberErrTip1'));

    const totalQty = filter.reduce((next, cur) => next += cur.qty, 0);
    if (totalQty !== totalNumber) return warning(window.$app.t('batchNumberErrTip'));

    onOk(filter);
  }, [batchNumbers, onOk, totalNumber]);

  const extra = useMemo(() => ([
    {
      dataIndex: 'batchNumber', render: (text: string, record: StockBatchNumber, index: number) => (
        <Input disabled={disabled} value={record.batchNumber} onChange={(e) => {
          syncBatchNumbers(index, 'batchNumber', e.target.value)
        }} />
      )
    },
    {
      dataIndex: 'qty', render: (text: string, record: BatchNumberProps, index: number) => (
        <InputNumber disabled={disabled} min={1} value={record.qty || 0} onChange={e => {
          syncBatchNumbers(index, 'qty', e)
        }} />
      )
    },
    {
      dataIndex: 'validityDate', render: (text: string, record: BatchNumberProps, index: number) => (
        <DatePicker disabled={disabled} value={moment(record.validityDate)} onChange={e => {
          syncBatchNumbers(index, 'validityDate', e)
        }} />
      )
    },
    {
      dataIndex: 'action', render: (text: string, record: BatchNumberProps, index: number) => !disabled ? (
        <Icon icon='delete' theme='warning' onClick={() => {
          setBatchNumbers(batchNumbers.filter((item, cindex) => index !== cindex))
        }} />
      ) : null
    }
  ]), [batchNumbers, disabled]);

  const okButtonProps = useMemo(() => ({ disabled }), [disabled]);

  return (
    <Modal width={784} visible={visible} onCancel={onCancel} wrapClassName='batchNumber'
      closable={false} onOk={_onOk} okButtonProps={okButtonProps}
      title={
        <Row align='middle' justify='space-between'>
          <span>{window.$app.t('batchNumberManage')}
          <span className={styles.spacing}>{window.$app.t('lineTotal')} {totalNumber}</span>
          </span>
          {!disabled && <Button onClick={addBatchNumber} ghost type='primary'>{window.$app.t('add')}</Button>}
        </Row>
      }>
      <div className={styles.box}>
        {stockBatchNumbers && (
          <>
            <Table ref={tableRef} rowSelectionType='checkbox' columns={sotckColumns} dataSource={stockBatchNumbers} />
            <div onClick={move} className={styles.move}>
              <Icon icon='&#xe618;' />
            </div>
          </>
        )}
        <Table scroll={scroll} columns={columns} dataSource={batchNumbers} extra={extra} />
      </div>
    </Modal>
  )
})
